package com.tree.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.backend.common.Result;
import com.tree.backend.entity.dto.PowerZoneDTO;
import com.tree.backend.entity.pojo.PowerZone;
import com.tree.backend.entity.vo.PowerZoneVO;
import com.tree.backend.mapper.PowerZoneMapper;
import com.tree.backend.service.IPowerZoneService;
import com.tree.backend.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PowerZoneServiceImpl extends ServiceImpl<PowerZoneMapper, PowerZone> implements IPowerZoneService {

    @Override
    public Result<Page<PowerZoneVO>> getList(PowerZoneDTO powerZoneDTO) {
        Page<PowerZone> powerZonePage = new Page<>(powerZoneDTO.getPage(), powerZoneDTO.getPageSize());
        LambdaQueryWrapper<PowerZone> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.like(StringUtils.isNotBlank(powerZoneDTO.getZoneName()), PowerZone::getZoneName, powerZoneDTO.getZoneName())
                .eq(powerZoneDTO.getStatus() != null, PowerZone::getStatus, powerZoneDTO.getStatus())
                .eq(UserContext.getCompanyId() != 0, PowerZone::getCompanyId, UserContext.getCompanyId())
                .ge(powerZoneDTO.getTotalCapacityMix() != null, PowerZone::getTotalCapacity, powerZoneDTO.getTotalCapacityMix())
                .le(powerZoneDTO.getTotalCapacityMax() != null, PowerZone::getTotalCapacity, powerZoneDTO.getTotalCapacityMax());

        Page<PowerZone> page = page(powerZonePage, lambdaQueryWrapper);


        Page<PowerZoneVO> powerZoneVOPage = new Page<>();
        BeanUtils.copyProperties(page, powerZoneVOPage);
        return Result.success(powerZoneVOPage);
    }
    
    @Override
    public Result<Map<Integer, String>> getIdNameMap() {
        // 查询当前企业的所有区域
        LambdaQueryWrapper<PowerZone> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserContext.getCompanyId() != 0, PowerZone::getCompanyId, UserContext.getCompanyId())
                .select(PowerZone::getId, PowerZone::getZoneName);
        
        // 将查询结果转换为ID-名称映射
        Map<Integer, String> idNameMap = list(queryWrapper).stream()
                .collect(Collectors.toMap(PowerZone::getId, PowerZone::getZoneName));
        
        return Result.success(idNameMap);
    }
}
